<?php


namespace Huang\PhpPersonalTools\wechat;


use EasyWeChat\Kernel\Exceptions\Exception;
use EasyWeChat\OfficialAccount\Application;

class WeChatOaService
{
    protected $app;

    protected $config;


    public function __construct($app_id, $app_secret, $token, $filepath = '')
    {
        $config = $this->getOaConfig($app_id, $app_secret, $token, $filepath = '');
        $this->config = $config;
        $this->app = new Application($config);
    }

    //tp6存储路径 app()->getRootPath() . 'runtime/wechat/' . date('Ym') . '/' . date('d') . '.log'
    public function getOaConfig($app_id, $app_secret, $token, $filepath = '')
    {
        return [
            'app_id' => $app_id,
            'secret' => $app_secret,
            'token' => $token,
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => $filepath
            ],
        ];
    }

    /**
     * 公众号-根据code获取微信信息
     * @description
     * @param string $code
     * @return mixed
     */
    public function getOaResByCode(string $code)
    {
        $response = $this->app->getOAuth()
            ->scopes(['snsapi_userinfo'])
            ->userFromCode($code)
            ->getRaw();

        if (!isset($response['openid']) || empty($response['openid'])) {
            throw new Exception('获取openID失败');
        }

        return $response;
    }


    /**
     * @notes 公众号跳转url
     * @param string $url
     * @return mixed
     * */
    public function getCodeUrl(string $url)
    {
        return $this->app->getOAuth()
            ->scopes(['snsapi_userinfo'])
            ->redirect($url);
    }

    /**
     * easywechat服务端
     * @description
     * @return mixed
     */
    public function getServer()
    {
        return $this->app->getServer();
    }

    /**
     * 创建公众号菜单
     * @description
     * @param array $buttons
     * @param array $matchRule
     * @return mixed
     */
    public function createMenu(array $buttons, array $matchRule = [])
    {
        if (!empty($matchRule)) {
            return $this->app->getClient()->postJson('cgi-bin/menu/addconditional', [
                'button' => $buttons,
                'matchrule' => $matchRule,
            ]);
        }

        return $this->app->getClient()->postJson('cgi-bin/menu/create', ['button' => $buttons]);
    }

    /**
     * 获取jssdkConfig
     *$jsApiList: [
     * 'onMenuShareTimeline',
     * 'onMenuShareAppMessage',
     * 'onMenuShareQQ',
     * 'onMenuShareWeibo',
     * 'onMenuShareQZone',
     * 'openLocation',
     * 'getLocation',
     * 'chooseWXPay',
     * 'updateAppMessageShareData',
     * 'updateTimelineShareData',
     * 'openAddress',
     * 'scanQRCode'
     * ]
     */
    public function getJsConfig($url, $jsApiList, $openTagList = [], $debug = false)
    {
        return $this->app->getUtils()->buildJsSdkConfig($url, $jsApiList, $openTagList, $debug);
    }
}
